/*!
 *  @author  xiaody <xiaody09@163.com>
 *  @description  Post class module.
 */

(function(){


'use strict';

// This module is only called when
// ${TiebaWhere.inside} == true.

var tieUrl = location.href, fkz = '';
if( tieUrl.match( '/p/' ) )
	fkz = tieUrl.split( '/p/' )[1].split( '?' )[0].split( '#' )[0];
else if( tieUrl.match( 'z=' ) )
	fkz = tieUrl.split( 'z=' )[1].split( '&' )[0].split( '#' )[0];
var pn = ( '' + tieUrl.match(/pn=\d+/) ).split( '=' )[1] || '1';


var PostSuperClass = {
	addFloorLink : function(){
		"use strict";
		var f = this.querySelector('.d_floor, .c_floor'),
			pid = this.getElementsByTagName('a')[1].attr('name');
		if(!f || !pid) {
			return this;
		}
		f.html('<a href="/p/'+fkz+'?pn='+pn+'&pid='+pid+'#'+pid+'" style="color:#222">'+f.innerHTML+'</a>');
		return this;
	},
	addIpLink : function(){
		"use strict";
		var td = $('.d_author_anonym', this);
		if(!td)
			return this;

		var ip = td.html().match(/(?:\d{1,3}\.){3}(?:\*|\d{1,3})/);
		var ipsearchlink = '<a href="http://www.baidu.com/s?wd=' +ip+ '" target="_blank">' +ip+ '</a>';
		td.html(td.html().replace(ip, ipsearchlink));

		Ajax.get('http://opendata.baidu.com/api.php?query='+ip+'&ie=utf8&format=json&tn=baidu&resource_id=6006', {
			success : function(r){
				r = JSON.parse(r);
				if(+r.status !== 0) {
					td.innerHTML += '<br />(幻想乡网友)';
				} else {
					var location = r.data[0].location;
					var text = location.split(' ')[0] + '网友';
					td.innerHTML += '<br />(' + text + ')';
				}

			}
		});
		return this;
	},
	decode : function(clubFlag){
		"use strict";

		var cc = clubFlag ? this.getElementsByTagName('div')[2] : this.getElementsByTagName('cc')[0],
			content = cc.firstElementChild || cc,
			pid = this.getElementsByTagName('a')[1].attr('name') || 0,
			doc = document;
		var c = cc.innerText;

		if(c.substring(0,8) === '#Base64#' || c.substring(0,10) === '/#Base64#/'){
			c = Base64.decode( c.split(/#Base64#\/?/)[1] );
			c = c.replace(/[\n\r]+/g, '<br />');
			cc.innerHTML =  '<p style="color: Green;" id="post_content_'+ pid +'">/#decoded Base64#/</p>' +
					'<p class="d_post_content">' + filterHTML(c) + '</p>';
			c = cc.innerText;
		} else if( c.substring(0,4) === '百度密语' && Miyu.decode(c) ) {
			cc.innerHTML = '<p style="color: Green;" id="post_content_'+ pid +'">/#decoded 百度密语#/</p>' +
					'<p class="d_post_content">' + filterHTML(Miyu.decode(c)) + '</p>';
			c = cc.innerText;
		}

		if(UUcode.generalDeRegExp.test(c)) {
			UUcode.Decode(content, RegExp.$1);
		}

		return this;
	},
	returnDOMObj : function(){
		return this;
	},
	pre : function(){
		var ret = this.previousElementSibling;
		if(ret && ret.className === this.className)
			return ret;
		else
			return null;
	},
	next : function(){
		var ret = this.nextElementSibling;
		if(ret && ret.className === this.className)
			return ret;
		else
			return null;
	},
	lit : function(){
		this.style.borderLeft = '1px solid #4D90F0';
		return this;
	},
	semiLit : function(){
		this.style.borderLeft = '1px solid #A7C7F7';
		return this;
	},
	focus : function(){
		if(this.pre())
			this.pre().semiLit();
		if(this.next())
			this.next().semiLit();
		this.lit();
	},
	focusIntoView : function(){
		"use strict";
		var height = window.getComputedStyle(this, null).getPropertyValue("height").match(/^\d+/),
			windowHeight = window.innerHeight,
			pageX = this.offset().top;
		var adjustment;
		if(height < windowHeight) {
			adjustment = (windowHeight - height) * 0.1;
		} else {
			adjustment = 0;
		}

		triggerScoll(pageX - adjustment);
		this.focus();
	},
	collapse : function(){
		"use strict";
		this.attr('BDB_collapse', true);

		var mainPart = this.getElementsByTagName('table')[0];
		mainPart.classList.add('hid');

		if($('.floor_cover', this)) {
			$('.floor_cover', this).classList.remove('hid');
			return this;
		}

		var PostInfo = JSON.parse( $('.p_post', this).dataset.field );
		var name = PostInfo.author.name, floorNum = PostInfo.content.floor;

		var coverContent = '<span class="d_name">' + '作者：' + name + '</span>' +
				'<span class=d_floor style=float:right>' + floorNum + '楼' + '</span>';
		var cover = document.createElement('table').attr('class', 'floor_cover').html(coverContent);

		if( $('.d_post_split', this) ) {
			mainPart.parentNode.insertBefore(cover, mainPart.parentNode.lastElementChild);
		} else { // For classic version
			mainPart.appendChild(cover);
		}

		return this;

	},
	expand : function(){
		"use strict";
		if(this.attr('BDB_collapse') == 'true') {
			this.removeAttribute('BDB_collapse');

			$('.floor_cover', this).classList.add('hid');

			var mainPart = this.getElementsByTagName('table')[0];
			mainPart.classList.remove('hid');
		}

		this.focusIntoView();
		return this;

	},
	toggle: function(){
		if(this.attr('BDB_collapse')) {
			return this.expand();
		} else {
			return this.collapse();
		}
	}

}

function triggerScoll(y){
	"use strict";

	triggerScoll.destination = y;

	var inter = function(){
		var _beforeStep = document.body.scrollTop;
		window.scrollBy( 0, (y - _beforeStep) * 0.33 << 0 );
		if(document.body.scrollTop !== _beforeStep && triggerScoll.destination === y)
			requestAnimationFrame(inter);
	};

	requestAnimationFrame(inter);
}

// Anti XSS for miyu.
function filterHTML(text){
	return text.replace(/<(?:[^i]|\s*?if).*?>/g, '').replace(/<img[^>]+?on\w{3,}[^>]*?>/ig, '');
}


// Expose to global.
window.PostSuperClass = PostSuperClass;


})();